package com.jml.zlhq.app.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.jml.zlhq.app.AppContext;
import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.adapter.MainFaXianAdapter;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.ui.LoginActivity.CheckBind;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.UIUtil;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;

public class qiandaoActivity extends BaseActivity {

	private String url;
	private TextView tvQiandao;
	private JSONArray tuijian;
	private QiandaoAdapter qdAdapter;
	private List<JSONObject> listItems = new ArrayList<JSONObject>();	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 2) {
				tvQiandao.setText(msg.getData().getString("text"));
			} else {
				listItems.clear();
				for (int i = 0; i < tuijian.length(); i++) {			
					try {
						listItems.add(tuijian.getJSONObject(i));
						System.out.println("tuijianGV.getJSONObject(i):" + tuijian.getJSONObject(i));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				qdAdapter.notifyDataSetChanged();
			}
		}
	};
	private LinearLayout loadpage;
	private ListView listview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.qiandao_activity);

		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		// LinearLayout rightLay = (LinearLayout)
		// findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		// rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.GONE);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setText("签到");
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setText("  ");
		TextView cityChosed = (TextView) findViewById(R.id.content_header_center_text2);
		cityChosed.setVisibility(View.GONE);

		tvQiandao = (TextView) findViewById(R.id.qiandao_info);
		qiandao();
		loadpage = (LinearLayout) findViewById(R.id.load_info_lay);
		

		listview = (ListView)findViewById(R.id.main_qiandao_list);
		qdAdapter = new QiandaoAdapter(activity, listItems);
		listview.setAdapter(qdAdapter);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				/*
				 * int index = new Long(id).intValue();
				 * toweb(BaseTools.getFrom("_id", listItems.get(index)), bToken,
				 * activity);
				 */
				
				Bundle data = new Bundle();
				data.putString("title", "活动详情");
				try {
					data.putString("id",listItems.get(position).getString("_id"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				UIUtil.openActivity(activity, HuodongDetailActivity.class, data);
			}
		});
		
		loadData(null);

	}

	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;

		default:
			break;
		}
	}

	public void qiandao() {
		Map<String, String> param = new HashMap<String, String>();
		if (appContext.isLogin())
			param.put("auth_token", appContext.getLoginUid());
		HttpService.postByText(URLs.MAIN_QIANDAO, param,
				new TextHttpResponseHandler() {
					@Override
					public void onSuccess(int arg0, Header[] arg1,
							String resultStr) {
						try {
							if (BuildConfig.DEBUG)
								Log.i("==result post==", resultStr);
							JSONObject result = new JSONObject(resultStr);
							Bundle data = new Bundle();
							data.putBoolean("refreash", false);
							if (result.getInt("status") == 0) {
								data.putString(
										"text",
										"今日签到：获得"
												+ BaseTools.getFrom(
														"data.fees", result,
														"0") + "金币!");
								data.putBoolean("refreash", true);
								LoginActivity.afterLogined(activity,
										new CheckBind() {
											@Override
											public void checkBind(String phone) {
												// TODO
											}
										});
							} else {
								data.putString("text",
										BaseTools.getFrom("message", result));
							}
							Message msg = new Message();
							msg.what = 2;
							msg.setData(data);
							handler.sendMessage(msg);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int arg0, Header[] arg1, String arg2,
							Throwable arg3) {
						UIUtil.ToastMessage(activity, "抱歉，访问失败");
					}
				});

	}

	public void loadData(Map<String, String> params) {
		// TODO Auto-generated method stub

		
		AppContext appCon = (AppContext) getApplication();
		//params.put("auth_token", appCon.getLoginUid());
		HttpService.getByText(URLs.QIANDAO_TUIJIAN, params,
				new TextHttpResponseHandler() {
					@Override
					public void onSuccess(int arg0, Header[] arg1,
							String resultStr) {
						try {
							if (BuildConfig.DEBUG)
								Log.i("==result post==", resultStr);
							JSONObject result = new JSONObject(resultStr);
							System.out.println("result TOKRN :" + result);
							if (result.getInt("status") == 0) {
								JSONObject data = result.getJSONObject("data");
								System.out.println("data:" + data);
																
								tuijian = data.getJSONArray("posts");
															
								
								handler.sendEmptyMessage(200);
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int arg0, Header[] arg1, String arg2,
							Throwable arg3) {
						UIUtil.ToastMessage(activity, "抱歉，访问失败");
					}
				});

	}

	@Override
	public void clearData() {
		// TODO Auto-generated method stub

	}

	class QiandaoAdapter extends BaseAdapter {
		private List<JSONObject> listItems;
		private AppContext appContext;
		@SuppressWarnings("unused")
		private Activity activity;

		public QiandaoAdapter(Activity activity, List<JSONObject> listItems) {
			this.listItems = listItems;
			this.appContext = (AppContext) activity.getApplication();
			this.activity = activity;
		}

		@Override
		public int getCount() {
			int count = listItems == null ? 0 : listItems.size();
			return count;
		}

		@Override
		public Object getItem(int position) {
			return listItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView,
				final ViewGroup parent) {
			convertView = createItem(position, convertView, parent);
			return convertView;
		}

		private View createItem(int position, View convertView,
				final ViewGroup parent) {
			ItemHolder holder = null;
			if (convertView == null) {
				holder = new ItemHolder();
				int main_tandian_item = R.layout.qiandao_list_item;
				convertView = LayoutInflater.from(appContext).inflate(
						main_tandian_item, null);
				holder.info = (TextView) convertView
						.findViewById(R.id.qd_tj_1);
				convertView.setTag(holder);
			} else {
				holder = (ItemHolder) convertView.getTag();
			}			
			try {
				holder.info.setText(listItems.get(position).getString("title"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return convertView;
		}
	}

	static class ItemHolder {
		
		public TextView info;
	}

}
